<!doctype html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Tauri App</title>
</head>

<body>
  <div style="display:flex;justify-content:center;align-items:center;flex-direction:column">
    <canvas style="width: 200px;" id="canvas"></canvas>
  </div>
  <script>
    let closeCameraWindow=false
    let init=false
    const canvas = document.getElementById("canvas")
    const ctx = canvas.getContext("2d")

    async function getCameraImg() {
      const { invoke } = window.__TAURI__.core
      return await invoke('get_camera_img');
    }
    
   
    async function show(imgData) {
      try{
        const blob = new Blob([new Uint8Array(imgData)], { type: 'image/png' });
        const bitmap = await createImageBitmap(blob);

        // 限制宽度为 200px，并按比例缩放高度
        const targetWidth = 200;
        const scale = targetWidth / bitmap.width;
        const targetHeight = bitmap.height * scale;

        canvas.width = targetWidth;
        canvas.height = targetHeight;

        ctx.drawImage(bitmap, 0, 0, targetWidth, targetHeight);
      }catch(e){
        ctx.font='30px 微软雅黑';
        const text = "摄像头打开失败";
        ctx.fillText(text, ( canvas.width - ctx.measureText(text).width ) / 2, 80);
      }
    }


    function checkMain () {
      
      const { getCurrentWindow, LogicalSize, Window } = window.__TAURI__.window

      Window.getByLabel('main').then( async (win) => {
        if (!win) {// 如果主窗口已经关闭
          //  console.log(getCurrentWindow().closeCameraWindow)
          closeCameraWindow=true
          getCurrentWindow().close()
        }
        
      })

      getCurrentWindow().setSize(new LogicalSize(250, canvas.height + 30));
    }

    
    setInterval(async () => {
      
      if (!init && window.__TAURI__) {
        const { getCurrentWindow, LogicalSize, Window } = window.__TAURI__.window
        const wv=getCurrentWindow()
        wv.onCloseRequested(async (event) => {
            //console.log("onclose======closeCameraWindow=%o",event)
            if(!closeCameraWindow){
              event.preventDefault()
            }
            closeCameraWindow=false
        })
        // 监听主动关闭事件
        const unlisten = await wv.listen("closeCameraWindow", e => {
          //console.log("================closeCameraWindow")
          closeCameraWindow=true
          wv.close()
        })
        //unlisten();
        init=true
      }

      checkMain()

      getCameraImg().then((imgData) => {
        show(imgData)
      })
    }, 1000);
  </script>
</body>

</html>